<template>
  <div class="sidebar" :class="{ 'collapsed': sidebarCollapsed }">
    <el-menu
      :collapse="sidebarCollapsed"
      :default-active="activeMenu"
      background-color="var(--el-menu-bg-color)"
      text-color="var(--el-menu-text-color)"
      active-text-color="var(--el-menu-active-text-color)"
      router
    >
      <template v-for="(route, index) in routes" :key="index">
        <el-sub-menu v-if="route.children && route.children.length > 0" :index="route.path">
          <template #title>
            <el-icon><component :is="route.meta?.icon" /></el-icon>
            <span>{{ $t(`menu.${route.meta?.title}`) }}</span>
          </template>
          <el-menu-item 
            v-for="child in route.children" 
            :key="child.path" 
            :index="`/${route.path}/${child.path}`"
          >
            <el-icon><component :is="child.meta?.icon" /></el-icon>
            <span>{{ $t(`menu.${child.meta?.title}`) }}</span>
          </el-menu-item>
        </el-sub-menu>
        <el-menu-item v-else :index="route.path">
          <el-icon><component :is="route.meta?.icon" /></el-icon>
          <span>{{ $t(`menu.${route.meta?.title}`) }}</span>
        </el-menu-item>
      </template>
    </el-menu>
    <div class="toggle-button" @click="toggleSidebar">
      <el-icon><Fold v-if="!sidebarCollapsed" /><Expand v-else /></el-icon>
    </div>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'
import { useConfigStore } from '@/store/modules/config'
import { Fold, Expand } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const configStore = useConfigStore()

const sidebarCollapsed = computed(() => configStore.sidebarCollapsed)
const activeMenu = computed(() => route.path)

// 获取路由表中的菜单项
const routes = computed(() => {
  return router.options.routes.find(r => r.path === '/').children || []
})

const toggleSidebar = () => {
  configStore.toggleSidebar()
}
</script>

<style scoped>
.sidebar {
  width: 220px;
  height: 100%;
  transition: width 0.3s;
  position: relative;
  background-color: var(--el-menu-bg-color);
}
.sidebar.collapsed {
  width: 64px;
}
.toggle-button {
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  text-align: center;
  cursor: pointer;
  padding: 10px 0;
}
</style>